

#include "undead_catapult.h"
#include "gamemanager.h"
#include "gamedatamanager.h"
#include "CCSkeletalSprite.h"
#include "cannonball.h"
#include "log.h"
#include "messagequeue.h"
#include "gamescene.h"

#define __super         Unit

UndeadCatapult::UndeadCatapult() {

}

UndeadCatapult::~UndeadCatapult() {

}

void UndeadCatapult::init(UnitInfo const &info, float unitScale) {
	__super::init(info, unitScale);
}

void UndeadCatapult::update(float ticks) {
	__super::update(ticks);
}

void UndeadCatapult::handleStateBirth(float ticks) {
	transformState(UnitState::idle);
}

void UndeadCatapult::handleStateAim(float ticks) {

}

void UndeadCatapult::handleStateAttack(float ticks) {
	if (sprite->animationIsDone()) {
		transformState(UnitState::reload);
	}
}

void UndeadCatapult::handleStateDying(float ticks) {
	if (sprite->animationIsDone()) {
		transformState(UnitState::died);
	}
}

void UndeadCatapult::handleStateIdle(float ticks) {
	if (gameScene->battleState == BattleState::standby) {
		return;
	}

	if (_timeElapsed >= attribute.reloadTime) {
		if(findDistantOpponent()) {
			transformState(UnitState::attack);
		}
	}
}

void UndeadCatapult::handleStateReload(float ticks) {
	if (sprite->animationIsDone()) {
		transformState(UnitState::idle);
	}
}

void UndeadCatapult::handleStateWalk(float ticks) {
	if (gameScene->battleState == BattleState::standby) {
		transformState(UnitState::idle);
	} else {
		move(ticks);

		if (arrivedTargetPosition) {
			transformState(UnitState::idle);
		} else if (_timeElapsed >= attribute.reloadTime) {
			if(findDistantOpponent()) {
				transformState(UnitState::walk_attack);
			}
		}
	}
}

void UndeadCatapult::handleStateWalkAim(float ticks) {

}

void UndeadCatapult::handleStateWalkAttack(float ticks) {
	if (sprite->animationIsDone()) {
		transformState(UnitState::walk_reload);
	}
}

void UndeadCatapult::handleStateWalkReload(float ticks) {
	if (sprite->animationIsDone()) {
		transformState(UnitState::walk);
	}
}

void UndeadCatapult::onAttack() {
	Unit *enemy = findDistantOpponent();
	if (enemy) {
		auto from = sprite->getBonePositionRelativeToWorld("skeleton_head");
		auto to = enemy->sprite->getBonePositionRelativeToWorld("asset_ballista_arrow");

		CannonBall *bullet = new CannonBall(from, to, &attribute);
		bullet->init();
		enemy->addBullet(bullet);
	}

	_timeElapsed = 0;
}
